import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'
import Home from '@/views/layout/home'
import Aq from '@/views/layout/aq'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'
import Search from '@/views/search'
import Result from '@/views/search/searchResult.vue'
import Acticle from '@/views/acticle'
import Edit from '@/views/layout/user/Edit.vue'
import store from '@/store'
import Chat from '@/views/layout/user/chat'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home'
  },
  {
    path: '/layout',
    component: Layout,
    children: [
      {
        path: 'home',
        component: Home,
        meta: {
          isalive: true
        }
      },
      {
        path: 'aq',
        component: Aq
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search/result',
    component: Result
  },
  {
    path: '/article/:id',
    component: Acticle
  },
  {
    path: '*',
    component: NotFound
  }
]
const loginURLs = ['/layout/user']
const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    if (loginURLs.some(item => item === to.path)) {
      router.push(`/login?back=${to.path}`)
    } else {
      next()
    }
  }
})
export default router
